package com.lincoln.framework.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;


/**
 * 直接返回数据
 * 
 * @author zwm
 */
public class ResponseRenderUtils {

	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(ResponseRenderUtils.class);

	private static final String ENCODING_PREFIX = "encoding:";
	private static final String NOCACHE_PREFIX = "no-cache:";
	private static final String ENCODING_DEFAULT = "UTF-8";
	private static final boolean NOCACHE_DEFAULT = true;

	/**
	 * 直接输出文本.
	 * 
	 */
	public static void renderText(HttpServletResponse response, final String text, final String... headers) {
		render(response, "text/plain", text, headers);
	}

	/**
	 * response直接返回文本内容
	 * 
	 * @param response
	 * @param contentType
	 * @param content
	 * @param headers
	 *            void
	 */
	public static void render(HttpServletResponse response, final String contentType, final String content,
			final String... headers) {
		try {
			// 分析headers参数
			String encoding = ENCODING_DEFAULT;
			boolean noCache = NOCACHE_DEFAULT;
			for (String header : headers) {
				String headerName = StringUtils.substringBefore(header, ":");
				String headerValue = StringUtils.substringAfter(header, ":");

				if (StringUtils.equalsIgnoreCase(headerName, ENCODING_PREFIX)) {
					encoding = headerValue;
				} else if (StringUtils.equalsIgnoreCase(headerName, NOCACHE_PREFIX)) {
					noCache = Boolean.parseBoolean(headerValue);
				} else
					throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
			}

			// 设置headers参数
			String fullContentType = contentType + ";charset=" + encoding;
			response.setContentType(fullContentType);
			if (noCache) {
				response.setHeader("Pragma", "No-cache");
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);
			}

			response.getWriter().write(content);

		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 文件下载
	 * @param response
	 * @param request
	 * @param filePath
	 * @param fileName
	 * @throws Exception
	 */
	public static void download(HttpServletResponse response, HttpServletRequest request, String filePath, String fileName) throws Exception {
		InputStream inputStream = null ;
		OutputStream outputStream = null;
		try{
		response.setContentType("application/octet-stream;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		inputStream = new FileInputStream(new File(filePath));
		String agent = request.getHeader("USER-AGENT");
		String encodeFileName = new String(fileName.replace(" ", "").getBytes("utf-8"), "ISO8859-1");
		if (null != agent && -1 != agent.indexOf("MSIE")) {
			encodeFileName = URLEncoder.encode(fileName.replace(" ", ""), "utf-8");
		}
		response.setHeader("Content-Disposition", "attachment;filename=\"" + encodeFileName + "\"");
		outputStream = response.getOutputStream();
		int i = -1;
		while ((i = inputStream.read()) != -1) {
			outputStream.write(i);
		}
		}
		catch (final IOException e) {
            System.out.println("出现IOException." + e);
        } 
		finally{
			  if (inputStream != null)
		inputStream.close();
		}
		if(outputStream!= null){
		outputStream.close();
		}
	}
}
